import React, { Component } from 'react';

import {getSongs} from "./util";

import Album from "./Component/Album";
import {togglePlay,changeSong,setUpdateCallback,setEndedCallback} from "./Component/Player";

class App extends Component {
  constructor(){
    super()
    this.state={
      playlists:[],
      playSrc:null,
      page:1,
      isPlaying:false,
      hasMore:true,
      loading:true,
      playProgress:0
    };
    this.play=this.play.bind(this);
    this.scrollHandler=this.scrollHandler.bind(this);
    this.loadMore=this.loadMore.bind(this);
  }
  componentDidMount(){
    getSongs(1).then(res=>{
      this.setState({
        playlists:res.data.tracksAudioPlay,
        loading:false,
      });
    });
    setEndedCallback(()=>{
      let curIndex=this.state.activeIndex;
      let count=this.state.playlists.length;
      if(curIndex>=count-1){
        this.play(this.state.playlists[0]);
      }else{
        this.play(this.state.playlists[curIndex+1]);
      }
    });
    window.addEventListener("scroll",this.scrollHandler);
  }
  scrollHandler(e){
    let offsetTop=document.documentElement.scrollTop;
    let screenHeight=window.outerHeight;
    let bodyHeight=document.body.offsetHeight;
    if(bodyHeight-screenHeight-offsetTop<=10){
      if(!this.state.loading&&this.state.hasMore)
      this.setState({
        loading:true
      },function(){
        this.loadMore();
      });
    }
  }
  loadMore(){
    if(this.state.hasMore){
      let curPage=this.state.page+1;
      getSongs(curPage).then(res=>{
        this.setState({
          page:curPage,
          playlists:[...this.state.playlists,...res.data.tracksAudioPlay],
          loading:false,
          hasMore:res.data.hasMore
        });
      });
    }
  }
  play(target){
    if(target.src===this.state.playSrc){
      const isPlaying=togglePlay();
      this.setState({
        isPlaying
      });
    }else{
      this.setState({
        playSrc:target.src,
        playName:target.trackName,
        activeIndex:target.index,
        isPlaying:true
      });
      changeSong(target.src);
      document.title=target.trackName
      setUpdateCallback((progress)=>{
        this.setState({
          playProgress:progress
        });
      });
    }
  }
  render() {
    const playlists=this.state.playlists;
    return (
      <div className="App">
        <ul className="playlist">
          {playlists.map(song=>(<Album key={song.trackId} {...song} clickHandle={this.play} progress={this.state.activeIndex===song.index&&this.state.playProgress} isActive={this.state.activeIndex===song.index} isPlaying={this.state.activeIndex===song.index&&this.state.isPlaying} />))}
        </ul>
      </div>
    );
  }
}

export default App;
